//
// Created by haoy on 2017/6/29.
//
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>

#include "layout_grid.hpp"

std::string layout_grid::_video_filter() {
    uint64_t bts = _begin_ts();
    uint64_t dur = _duration();
    // determine grid dimension
    dimension grid_dim {0, 0};

    for (auto& i : video_tracks_) {
        if (i.dim.w > grid_dim.w) {
            grid_dim.w = i.dim.w;
        }
        if (i.dim.h > grid_dim.h) {
            grid_dim.h = i.dim.h;
        }
    }

    int r = 1;
    int s = 1;
    while (s < video_tracks_.size()) {
        s = std::pow(++r, 2);
    }

    int w_grids = r;
    int h_grids = r;

    std::cout << "grids=" << w_grids << "x" << h_grids << std::endl;
// stack is slower
//    std::unique_ptr<stacked_block> top_block(new stacked_block("", true));
//
//    for (int row = 0; row < h_grids && video_tracks_.size() > 0; ++row) {
//        std::ostringstream w1;
//        w1 << "row-" << row;
//        std::unique_ptr<stacked_block> row_block(new stacked_block(w1.str(), false));
//        for (int col = 0; col < w_grids; ++col) {
//            if (video_tracks_.size()) {
//                std::ostringstream w2;
//                w2 << "blk-" << row << "-" << col;
//                auto& v = video_tracks_.front(); video_tracks_.pop_front();
//                row_block->stack(new source_block(v, grid_dim, w2.str(), v.begin_ts - bts));
//
//            } else {
//                std::ostringstream w3;
//                w3 << "blk-" << row << "-" << col;
//                row_block->stack(new pad_block(w3.str() ,grid_dim));
//            }
//        }
//        top_block->stack(std::move(row_block.release()));
//    }
    background_block bg(dimension(0, 0), "bg", dur);

    int i = 0;
    for (int row = 0; row < h_grids && video_tracks_.size() > 0; ++row) {
        std::ostringstream w1;
        int y = grid_dim.h * row;
        for (int col = 0; col < w_grids; ++col) {
            int x = grid_dim.w * col;
            if (i < video_tracks_.size()) {
                std::ostringstream bname;
                bname << "s-" << row << "-" << col;
                auto v = video_tracks_[i];
                bg.overlay(filter_block(v.filter, v.dim, bname.str(), v.begin_ts, v.duration_ms), x, y);
                ++i;
            }
        }
    }
    return std::string(bg.filter(bts));
}
